package com.ly.mpayment.rest.up.jiangren;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Component
@Path("jiangren")
public class JiangRenRest {
    Logger logger = Logger.getLogger(JiangRenRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;



    @Path("callBack")
    @POST
    public String callBack(@RequestBody String body) {
        logger.info("jiangren_callback:"+body);
        if(StringUtils.isBlank(body)){
            return "fail";
        }
        //充值状态，success表示成功，fail表示失败
        JSONObject data = JSONObject.parseObject(body);
        UpOrder order = upOrderService.findById(data.getString("euserOrderNo"));
        if (order != null && data.getString("orderStatus").equals("success") && order.getStatus() == Config.status[0]) {
            order.setRemark(StringUtils.isBlank(data.getString("serialNumber")) ? data.getString("serialNumber") :
                    data.getString("resultMsg"));
            RechargeRest.successUpOrder.add(order);
            return "success";
        } else if (order != null && order.getStatus() == Config.status[0] && data.getString("orderStatus").equals("fail")) {
            order.setRemark(data.getString("resultMsg"));
            RechargeRest.failtUpOrder.add(order);
            return "success";
        } else {
            this.upOrderService.addOrderMsg(order,data.getString("resultMsg"));
            logger.info("jiangren_not_found_order:" + data.getString("order_status") + "," + (order == null ? "" : order.getUpphonenum()));
        }
        return "fail";
    }


    public void commitOrder(UpOrder order, UpShopInfo shop) {
        JSONObject data = new JSONObject();
        data.put("euserId",shop.getAppId());
        data.put("timestamp", System.currentTimeMillis());
        data.put("parValue",order.getUpShopPro().getUpfacevalue());
        data.put("accountNo",order.getUpphonenum());
        data.put("euserOrderNo",order.getUporderuuid());
        data.put("sign", MD5.md5(shop.getUpkey()+ StringSort.doSignValue(data) +shop.getUpkey()));
        String result = HttpClient.post(shop.getOrderCommitAddress(),data.toString());
        logger.info("commitOrder_jiangren:" + result + ":" + shop.getOrderCommitAddress().concat("?").concat(data.toString()));
        if (!StringUtils.isBlank(result)) {
            try{
                JSONObject json = JSONObject.parseObject(result);
                if (json.containsKey("retCode") && json.getString("retCode").equals("0") ) {
                    this.upOrderService.updateUpOrderMsg(order,json.getString("orderNo"),json.containsKey("retMsg") ?
                            json.getString("retMsg") : "");
                } else if (json.containsKey("retCode") && errorCode.contains(json.getString("retCode"))){
                    order.setRemark(json.getString("retMsg"));
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    upOrderService.updateUpOrderArtificial(order, "",json.getString("retMsg"));
                }
            }catch (Exception e){
                e.printStackTrace();
                upOrderService.updateUpOrderArtificial(order,"","提单失败,人工");
            }
        } else {
            this.upOrderService.updateUpOrderArtificial(order, "","人工");
            logger.info("commitOrder_error:" + order.getUpphonenum());
        }
    }

    Set<String> errorCode = new HashSet<String>(){{
        add("1");
    }};



    /**
     * 订单查询
     *
     * @param order
     * @param shop
     */
    public void queryOrder(UpOrder order, UpShopInfo shop) {
        JSONObject data = new JSONObject();
        data.put("euserId",shop.getAppId());
        data.put("timestamp", System.currentTimeMillis());
        data.put("euserOrderNo",order.getUporderuuid());
        data.put("sign", MD5.md5( shop.getUpkey()+ StringSort.doSignValue(data) +shop.getUpkey()));

        String result = HttpClient.post(shop.getOrderStatusAddress(),data.toString());
        logger.info("jiangrenqueryOrder:" + shop.getOrderStatusAddress()+ ":" + result+","+data);
        if (!StringUtils.isBlank(result)) {
            JSONObject json = JSONObject.parseObject(result);
            //{"orderNo":"2022091110111822d8a4","salePrice":49.0000,"orderStatus":"success","retCode":"0","retMsg":"查询成功"}
            if (json.containsKey("retCode") && json.getString("retCode").equals("0")) {
                UpOrder upOrder = upOrderService.findByUpOrderId(order.getUporderuuid());
                if (upOrder != null && json.getString("orderStatus").equals("success") && order.getStatus() == Config.status[0]) {
                    upOrder.setRemark( json.containsKey("retMsg") ? json.getString("retMsg") :
                            json.getString("retMsg"));
                    RechargeRest.successUpOrder.add(upOrder);
                } else if (upOrder != null && order.getStatus() == Config.status[0] && json.getString("orderStatus").equals("fail") ) {
                    upOrder.setRemark(json.getString("retMsg"));
                    RechargeRest.failtUpOrder.add(upOrder);
                } else {
                    this.upOrderService.addOrderMsg(order,json.getString("retMsg"));
                    logger.info("jiangren_not_found_order:" + upOrder.getUpphonenum());
                }
            } else {
                logger.info("jiangren_not_found_order:" + order.getUpphonenum());
            }
        }
    }

}
